package top.mccat.shirospring.shiro.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import top.mccat.shirospring.pojo.User;
import top.mccat.shirospring.service.UserService;

/**
 * @author raven
 */
public class UserRealm extends AuthorizingRealm {
    private Logger log = LoggerFactory.getLogger(UserRealm.class);
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.debug("执行=>授权验证操作");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User primaryPrincipal = (User) principalCollection.getPrimaryPrincipal();
        authorizationInfo.addStringPermission(primaryPrincipal.getPermission());
        return authorizationInfo;
    }
    @Autowired
    private UserService userService;
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.debug("执行=>认证信息操作");
        //获取当前用户数据
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String tokenName = token.getUsername();
        if(tokenName==null || "".equals(tokenName)){
            return null;
        }
        User user = userService.queryUserByName(tokenName);
        if(user == null){
            //如果用户为空代表没找到
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("user",user);
        return new SimpleAccount(user,user.getPassword(),user.getUsername());
    }
}
